<template>
  <view class="goods-add">
    <view class="form-container">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="section-title">基本信息</view>
        
        <view class="form-item">
          <view class="form-label required">商品名称</view>
          <input 
            class="form-input" 
            v-model="formData.goodsName" 
            placeholder="请输入商品名称"
            maxlength="50"
          />
        </view>

        <view class="form-item">
          <view class="form-label required">商品分类</view>
          <picker 
            class="form-picker"
            mode="selector"
            :range="categoryOptions"
            :range-key="'label'"
            :value="categoryIndex"
            @change="onCategoryChange"
          >
            <view class="picker-value">
              <text :class="{'placeholder': formData.goodsCategory === ''}">
                {{ formData.goodsCategory !== '' ? categoryOptions[categoryIndex].label : '请选择商品分类' }}
              </text>
              <uni-icons type="bottom" size="16" color="#999"></uni-icons>
            </view>
          </picker>
        </view>

        <!-- <view class="form-item">
          <view class="form-label">计量单位</view>
          <input 
            class="form-input" 
            v-model="formData.unit" 
            placeholder="请输入计量单位（如：斤、千克、箱）"
            maxlength="20"
          />
        </view> -->
      </view>

      <!-- 产地信息 -->
      <!-- <view class="form-section">
        <view class="section-title">产地信息</view>
        
        <view class="form-item">
          <view class="form-label">产地</view>
          <picker 
            class="form-picker"
            mode="multiSelector"
            :value="regionIndex"
            :range="regionRange"
            range-key="label"
            @change="onRegionChange"
            @columnchange="onColumnChange"
          >
            <view class="picker-value">
              <text :class="{'placeholder': !hasOrigin}">
                {{ originText || '请选择产地' }}
              </text>
              <uni-icons type="bottom" size="16" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
      </view> -->

      <!-- 其他信息 -->
      <view class="form-section">
        <view class="section-title">其他信息</view>
        
        <!-- <view class="form-item">
          <view class="form-label">排序号</view>
          <input 
            class="form-input" 
            v-model.number="formData.sortOrder" 
            type="number"
            placeholder="请输入排序号（数字越小越靠前）"
          />
        </view> -->

        <view class="form-item">
          <view class="form-label">备注</view>
          <textarea 
            class="form-textarea"
            v-model="formData.remark"
            placeholder="请输入备注信息"
            maxlength="200"
          />
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <button class="btn-cancel" @click="cancel">取消</button>
      <button class="btn-submit" @click="submit">保存</button>
    </view>
  </view>
</template>

<script>
import { addGoods } from '@/api/business/goods.js'
import { getProvinces, getCities, getDistricts } from '@/api/system/region.js'

export default {
  data() {
    return {
      formData: {
        goodsName: '',
        goodsCategory: '',
        unit: 'kg',
        originProvince: '',
        originCity: '',
        originDistrict: '',
        sortOrder: 0,
        remark: '',
        status: '0'
      },
      categoryOptions: [
        { value: '0', label: '种植业' },
        { value: '1', label: '养殖业' },
        { value: '2', label: '畜牧业' }
      ],
      categoryIndex: -1,
      // 地区相关数据
      regionData: [],
      provinces: [],
      cities: [],
      districts: [],
      regionIndex: [0, 0, 0],
      regionRange: [[], [], []]
    }
  },
  onLoad() {
    this.loadProvinces()
  },
  computed: {
    hasOrigin() {
      return this.formData.originProvince || this.formData.originCity || this.formData.originDistrict
    },
    originText() {
      let text = []
      if (this.formData.originProvince) text.push(this.formData.originProvince)
      if (this.formData.originCity) text.push(this.formData.originCity)
      if (this.formData.originDistrict) text.push(this.formData.originDistrict)
      return text.join(' ')
    }
  },
  methods: {
    // 加载省份数据
    async loadProvinces() {
      try {
        const res = await getProvinces()
        if (res.code === 200) {
          this.provinces = res.data || []
          this.regionRange[0] = this.provinces.map(item => ({ 
            label: item.regionName, 
            value: item.regionName,
            id: item.id
          }))
          
          // 默认加载第一个省份的城市
          if (this.provinces.length > 0) {
            this.loadCities(this.provinces[0].id, 0)
          }
        }
      } catch (error) {
        console.error('加载省份数据失败:', error)
        uni.showToast({
          title: '加载省份数据失败',
          icon: 'none'
        })
      }
    },

    // 加载城市数据
    async loadCities(provinceId, provinceIndex) {
      try {
        const res = await getCities(provinceId)
        if (res.code === 200) {
          this.cities = res.data || []
          this.regionRange[1] = this.cities.map(item => ({ 
            label: item.regionName, 
            value: item.regionName,
            id: item.id
          }))
          
          // 默认加载第一个城市的区县
          if (this.cities.length > 0) {
            this.loadDistricts(this.cities[0].id, 0)
          }
        }
      } catch (error) {
        console.error('加载城市数据失败:', error)
      }
    },

    // 加载区县数据
    async loadDistricts(cityId, cityIndex) {
      try {
        const res = await getDistricts(cityId)
        if (res.code === 200) {
          this.districts = res.data || []
          this.regionRange[2] = this.districts.map(item => ({ 
            label: item.regionName, 
            value: item.regionName,
            id: item.id
          }))
        }
      } catch (error) {
        console.error('加载区县数据失败:', error)
      }
    },

    // 分类选择变化
    onCategoryChange(e) {
      this.categoryIndex = e.detail.value
      this.formData.goodsCategory = this.categoryOptions[this.categoryIndex].value
    },

    // 地区选择变化
    onRegionChange(e) {
      const indexes = e.detail.value
      this.regionIndex = indexes
      
      // 更新表单数据
      if (this.regionRange[0][indexes[0]]) {
        this.formData.originProvince = this.regionRange[0][indexes[0]].value
      }
      if (this.regionRange[1][indexes[1]]) {
        this.formData.originCity = this.regionRange[1][indexes[1]].value
      }
      if (this.regionRange[2][indexes[2]]) {
        this.formData.originDistrict = this.regionRange[2][indexes[2]].value
      }
    },
    
    // 地区列变化（级联选择）
    async onColumnChange(e) {
      const column = e.detail.column
      const row = e.detail.value
      
      // 更新索引
      this.regionIndex[column] = row
      
      if (column === 0) {
        // 省份变化，加载对应的城市
        const province = this.provinces[row]
        if (province) {
          await this.loadCities(province.id, row)
          this.regionIndex[1] = 0
          this.regionIndex[2] = 0
        }
      } else if (column === 1) {
        // 城市变化，加载对应的区县
        const city = this.cities[row]
        if (city) {
          await this.loadDistricts(city.id, row)
          this.regionIndex[2] = 0
        }
      }
      
      // 触发重新渲染
      this.$forceUpdate()
    },

    // 验证表单
    validateForm() {
      if (!this.formData.goodsName) {
        uni.showToast({
          title: '请输入商品名称',
          icon: 'none'
        })
        return false
      }
      if (this.formData.goodsCategory === '') {
        uni.showToast({
          title: '请选择商品分类',
          icon: 'none'
        })
        return false
      }
      // if (!this.formData.unit) {
      //   uni.showToast({
      //     title: '请输入计量单位',
      //     icon: 'none'
      //   })
      //   return false
      // }
      return true
    },

    // 取消
    cancel() {
      uni.navigateBack()
    },

    // 提交
    async submit() {
      if (!this.validateForm()) return

      try {
        uni.showLoading({
          title: '保存中...',
          mask: true
        })

        const response = await addGoods(this.formData)
        
        if (response.code === 200) {
          uni.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 2000
          })
          
          // 设置刷新标记
          const pages = getCurrentPages()
          const prevPage = pages[pages.length - 2]
          if (prevPage) {
            prevPage.needRefresh = true
          }
          
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: response.msg || '添加失败',
            icon: 'none',
            duration: 2000
          })
        }
      } catch (error) {
        console.error('添加商品失败:', error)
        uni.showToast({
          title: '添加失败，请重试',
          icon: 'none',
          duration: 2000
        })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style scoped>
.goods-add {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.form-container {
  padding: 20rpx;
}

/* 表单区块 */
.form-section {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 30rpx;
  padding-left: 16rpx;
  position: relative;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 32rpx;
  background-color: #52c41a;
  border-radius: 3rpx;
}

/* 表单项 */
.form-item {
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 16rpx;
  display: flex;
  align-items: center;
}

.form-label.required::before {
  content: '*';
  color: #ff4d4f;
  margin-right: 8rpx;
}

.form-input {
  width: 100%;
  height: 88rpx;
  padding: 0 24rpx;
  font-size: 30rpx;
  color: #333;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  box-sizing: border-box;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 24rpx;
  font-size: 30rpx;
  color: #333;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  box-sizing: border-box;
}

/* 选择器 */
.form-picker {
  width: 100%;
  background-color: #f5f5f5;
  border-radius: 12rpx;
}

.picker-value {
  height: 88rpx;
  padding: 0 24rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.picker-value text {
  font-size: 30rpx;
  color: #333;
}

.picker-value text.placeholder {
  color: #999;
}

/* 底部按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  display: flex;
  gap: 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.btn-cancel, .btn-submit {
  flex: 1;
  height: 88rpx;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 44rpx;
  border: none;
}

.btn-cancel {
  background-color: #f5f5f5;
  color: #666;
}

.btn-submit {
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  color: #fff;
}
</style>